import 'dart:async';
import 'dart:math';

import 'package:get/get.dart';
import 'package:number_spark_flutter/config/ns_base_controller.dart';
import 'package:number_spark_flutter/db_manager/bean/ns_record_bean.dart';
import 'package:number_spark_flutter/pages/ns_home/single/ns_single_logic.dart';
import 'package:number_spark_flutter/utils/ns_db_utils.dart';
import 'package:number_spark_flutter/utils/ns_user_utils.dart';

import 'view/double_result_dialog.dart';

const String idCorrectCount = 'correctCount';
const String idMyQuestion = 'idMyQuestion';
const String idYourQuestion = 'idYourQuestion';

class NSDoubleLogic extends NSBaseController {
  Timer? _timer;
  int countDown = 60;

  List<Question> questionsList = [];

  int myIndex = 0;
  int yourIndex = 0;

  @override
  void onInit() {
    super.onInit();
    // 生成 10 道题目
    for (int i = 0; i < 1000; i++) {
      questionsList.add(generateQuestion());
    }
    onStartTimer();
  }

  onStartTimer() {
    _timer ??= Timer.periodic(const Duration(seconds: 1), (timer) {
      countDown--;
      if (countDown == 0) {
        _timer?.cancel();
        _timer = null;
        onShowResultDialog();
      }
      update([idCountDown]);
    });
  }

  void onShowResultDialog() {
    bool isMeWin = questionsList.where((element) => element.myAnswer == element.answer).length > questionsList.where((element) => element.yourAnswer == element.answer).length;
    bool isDraw = questionsList.where((element) => element.myAnswer == element.answer).length == questionsList.where((element) => element.yourAnswer == element.answer).length;
    Get.dialog(
      DoubleResultDialog(isMeWin: isMeWin, isDraw: isDraw),
    );
  }

  doClickMyOption(int answer) {
    questionsList[myIndex].myAnswer = answer;
    myIndex++;
    update([idCorrectCount, idMyQuestion]);
  }

  doClickYourOption(int answer) {
    questionsList[yourIndex].yourAnswer = answer;
    yourIndex++;
    update([idCorrectCount, idYourQuestion]);
  }

  @override
  void onClose() {
    super.onClose();
    _timer?.cancel();
    _timer = null;
    bool isMeWin = questionsList.where((element) => element.myAnswer == element.answer).length > questionsList.where((element) => element.yourAnswer == element.answer).length;
    NSDBUtils.instance.daoRecord.insert([
      NSRecordBean(
        type: 'double',
        myCorrectCount: questionsList.where((element) => element.myAnswer == element.answer).length,
        yourCorrectCount: questionsList.where((element) => element.yourAnswer == element.answer).length,
        isMeWin: isMeWin,
        userId: NSUserUtils.getId(),
      )
    ]);
  }
}
